<?php

namespace IDock\Insurance\AMIC\Request;

use GuzzleHttp\Psr7\Stream;
use IDock\Insurance\AMIC\Response\UploadFileResponse;
use IDock\Visitor\UploadFileVisitor;
use ZipArchive;

class UploadFileRequest extends AllAMICRequest
{
    public $requestType = 'N0208';

    protected $response = UploadFileResponse::class;

    protected $urlTip = '影像上传';

    protected $inLog = true;

    /**
     * @var  UploadFileVisitor $visitor
     */
    protected $visitor;

    public function generate(): array
    {
        $zip = new ZipArchive();
        $tmpDir = __DIR__ . '/../Zip/' . sha1(mt_rand(1000, 9999) . uniqid());
        if (!file_exists($tmpDir)) {
            mkdir($tmpDir, 0775, true);
        }
        $zipPath = $tmpDir . '/HXY' . date('YmdHis') . '.zip';
        $zip->open($zipPath, ZipArchive::CREATE);
        foreach ($this->visitor->fileList as $value) {
            $basename = iconv('UTF-8', 'GBK//IGNORE', basename($value['url']));
            $filename = $tmpDir . '/' . sha1(mt_rand(100000000, 999999999)) . $basename;
            if (file_put_contents($filename, file_get_contents($value['url']))) {
                var_dump($zip->addFile($filename, basename($filename)));
            }
        }
        if (!$zip->close()) {
            throw new \Exception("压缩文件失败");
        }
        $arr = [
            'fileBase' => [
                'zipName' => basename($zipPath),
                'bussNo' => '',
                'userCode' => $this->visitor->argc['appOperatorCode'] ?? '',
                'comCode' => '',
                'zipCode' => base64_encode(file_get_contents($zipPath)),
                'orderNo' => $this->visitor->argc['orderNo'] ?? '',
            ],
        ];
        $this->deleteDir($tmpDir);
        return $arr;
    }

    public function deleteDir($dir)
    {
        if (!file_exists($dir)) {
            return;
        }

        if (is_dir($dir)) {
            $files = scandir($dir);
            foreach ($files as $file) {
                if ($file != '.' && $file != '..') {
                    self::deleteDir($dir . '/' . $file);
                }
            }
            rmdir($dir);
        } else {
            unlink($dir);
        }
    }
}
